package com.sheng.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: 王胜
 * @Date 2022/11/19 17:03
 */
@Component
@Slf4j
public class JwtUtils {

    //这里的token属性配置最好写在配置文件中，这里为了方面直接写成静态属性
    public static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;//token到期时间24H，毫秒为单位
    public static final long REFRESH_EXPIRE_TIME = 24 * 60 * 60;//RedisToken到期时间为24H，秒为单位
    private static final String TOKEN_SECRET = "superman";  //密钥盐

    //生成token的方法
    public static String sign(String account, Long currentTime) {

        String token = null;
        try {
            Date expireAt = new Date(currentTime + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("admin")//发行人
                    .withClaim("account", account)//存放数据
                    .withClaim("currentTime", currentTime)
                    .withExpiresAt(expireAt)//过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException je) {

        }
        return token;
    }


    /**
     * @param : [token]
     * @return : java.lang.Boolean
     * @throws :
     * @Description ：token验证
     * @author : lj
     * @date : 2020-1-31 22:59
     */
    public static Boolean verify(String token) {

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("admin").build();//创建token验证器

        try {
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            log.info("认证通过：");
            log.info("account: " + decodedJWT.getClaim("account").asString());
            log.info("过期时间：      " + decodedJWT.getExpiresAt());
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public static String getAccount(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim("account").asString();

        } catch (JWTCreationException e) {
            return null;
        }
    }

    public static Long getCurrentTime(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim("currentTime").asLong();

        } catch (JWTCreationException e) {
            return null;
        }
    }

}
